package com.jfinal.complex.kit;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.complex.exception.TableSplitException;
import com.jfinal.complex.tablesplit.interfaces.ITableSplitFactory;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

public class TableSplitKit {

	private static ITableSplitFactory tableSplitFactory = null;

	public static ITableSplitFactory getTableSplitFactory() {
		return tableSplitFactory;
	}

	public static void setTableSplitFactory(ITableSplitFactory tableSplitFactory) {
		TableSplitKit.tableSplitFactory = tableSplitFactory;
	}

	public static String generateSQL(String sql, Map<String, Object> attrs) {
		if (tableSplitFactory == null) {
			throw new TableSplitException(
					"ITableSplitFactory tableSplitFactory 为null");
		}
		return tableSplitFactory.createQuerySQL(sql, attrs);
	}
	
	public static <T extends Model<T>> List<T> find(List<T> models,String sql,Object... paras ){
		if(models==null || models.size()==0){
			return new ArrayList<T>();
		}
		
		StringBuilder buildSql = new StringBuilder();
		List<Object> list = new ArrayList<Object>();
		
		for(int i=0;i<models.size();i++){
			T model = models.get(i);
			if(i > 0){
				buildSql.append(" union all ");
			}
			buildSql.append(generateSQL(sql,model.getModelMap()));
			
			for (int j = 0; j < paras.length; j++) {
				list.add(paras[j]);
			}
		}
		return models.get(0).find(buildSql.toString(), list.toArray());
	}
	
	public static <T extends Model<T>> List<T> find(List<T> models,String sql){
		return find(models, sql, new Object[0]);
	}
}
